﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility.Utils.SnowflakeUtils;

namespace Utility.Utils
{
    public class IdUtil
    {
        public static string NewId()
        {
            return Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 生成有序的guid
        /// </summary>
        /// <returns></returns>
        public static Guid NewGuidId()
        {
            return SequentialGuidGenerator.NewSequentialGuid(SequentialGuidType.SequentialAsString);
        }

        /// <summary>
        /// 雪花ID
        /// </summary>
        /// <returns></returns>
        public static long NewLongId()
        {
            return Snowflake.Instance.NextId();
        }

        public static string NewIdByTimeX34(string prefix)
        {
            return $"{prefix}{NewIdByTimeX34()}";
        }

        public static string NewIdByTime(ushort randomLength = 0)
        {
            string text = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            if (randomLength > 0)
            {
                string text2 = new Random().Next(1, randomLength * 10).ToString().PadLeft(randomLength, '0');
                text += text2;
            }
            return text;
        }

        public static string NewIdByTimeX34()
        {
            return X10ConvetTo34((long)(DateTime.Now - new DateTime(2018, 1, 1)).TotalMilliseconds);
        }

        public static string X10ConvetTo34(long val)
        {
            string text = string.Empty;
            string text2 = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
            int length = text2.Length;
            while (val >= length)
            {
                text = text2[(int)(val % length)] + text;
                val /= length;
            }
            if (val >= 0)
            {
                text = text2[(int)val] + text;
            }
            return text;
        }

        public static long X34ConvertTo10(string val)
        {
            long num = 0L;
            if (string.IsNullOrWhiteSpace(val))
            {
                return num;
            }
            string text = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
            int length = text.Length;
            string text2 = val.ToUpper();
            int length2 = text2.Length;
            for (int num2 = length2; num2 > 0; num2--)
            {
                int num3 = text.IndexOf(text2[num2 - 1]);
                if (num3 == -1)
                {
                    throw new ArgumentException("参数不是有效的34进制数据,34进制数据仅包括1-9,A-Z(除O,I)");
                }
                num += num3 * Convert.ToInt32(Math.Pow(length, length2 - num2));
            }
            return num;
        }


    }
}
